//抽奖相关
//获取活动编号
const getPromotNo = function(){
	return new Promise((resolve,reject) =>{
           lotteryTool.ajax({
           	  param:{},
           	  success:function(data){
           	  	 let result = data ;
           	  	 if(result.returnCode ="000000"){
           	  	 	//lotteryTool.promotNo = result.promotNo;
           	  	 	resolve(result.promotNo)
           	  	 }else{
           	  	 	Login2()
           	  	 }
                 
           	  },
           	  error:function(data){
           	  	reject(data.message)
           	  }
           })
	  }
	)
}
//所有抽奖记录查询  拿不到活动编号是不能进行查询的
const allLotteryRecords = function(promotNo){
    return new Promise((resolve,reject)=>{
    	 lotteryTool.ajax({
						param : {
							"promotNo": promotNo,
							//"userCode": userInfor.userCode,//$("#uid").val()
							"sessionId": userInfor.sessionId//$("#ssid").val()
						},
						port : 'C_APP_3023', //中奖纪录
						success : function(data){
							let result = data ;
							let $awardRecords = $("#awardRecords"),
								//$falseAwardRecords = $("#falseAwardRecords"),
								
							if(result.returnCode =="000000"){
								// resolve(data)  是否具有假数据需要确认
							    if(result.userRecord.length == 0){
									$awardRecords.empty().append("<li style='text-align: center;'>暂无中奖纪录</li>");
								}else{
									let html = '',
										cls = "even";
									// for(var i=0,l=result.falseAwardRecords.length; i<l;i++){
									// 	if(i%2){
									// 		cls = "even"      //偶数所加的类名
									// 	}else{
									// 		cls = "old"       //奇数类名
									// 	}
									// 	html += '<li class="'+cls+'"><span>恭喜'+result.falseAwardRecords[i].phone+'</span><span>抽中</span><span class="red">'+result.falseAwardRecords[i].awardname+'</span></li>';
									// }
									for(let i=0,l=result.userRecord.length; i<l;i++){
										if(i%2){
											cls = "even"      //偶数所加的类名
										}else{
											cls = "old"       //奇数类名
										}
										html += `<li  class="${cls}"><span class="span1">恭喜${result.userRecord[i].phone}</span><span class="span2">抽中</span><span class="span3 red">${lotteryTool.parseNum(result.userRecord[i].couponValue)} ${lotteryTool.getUnit(result.userRecord[i].couponType)} ${lotteryTool.getPrizeName(result.userRecord[i].couponType)}</span></li>`;
									}
									$awardRecords.empty().append(html);
									setInterval(function(){autoScroll(".kindLists")},2000);
								}
																
							}else{
								Login()
							}							
							
						},
						error : function(err){
							console.log(err)
				    }
			});

    })
}

//用户抽奖记录查询  拿不到活动编号是不能进行查询的
const adminLotteryRecords = function (promotNo){
	return new Promise((resolve,reject)=>{
		lotteryTool.ajax({
				param : {
						"promotNo": promotNo,
						"userCode": userInfor.userCode,//$("#uid").val()
						"sessionId": userInfor.sessionId//$("#ssid").val()
					},
					port : 'C_APP_3022', //用户中奖纪录
					success : function(data){
						let result = data;
						let $personAwardRecords = $("#personAwardRecords");
						if(result.returnCode == "000000"){
							if(result.drawUserRecord.length == 0){
								$personAwardRecords.empty().append('<li class="noRecord"><img src="images/complianceOn-imgs/noRecord.png"></li>');
							}else{
								var cont = `<div class="bd"><ul class="rtit">
											<li><span>时间</span><span>奖品</span></li></ul><ul class="rcont">`;
								for(let i=0; i< result.drawUserRecord.length;i++){
									 cont += `<li><span>${lotteryTool.formatDate(result.drawUserRecord[i].createTime)}</span><span>${lotteryTool.getPrizeName(result.drawUserRecord[i].couponType)}+${lotteryTool.parseNum(result.drawUserRecord[i].couponValue)} ${lotteryTool.getUnit(result.drawUserRecord[i].couponType)}</span></li>`;
								}
								cont += `</ul></div>`;
								$personAwardRecords.empty().append(cont);
							}
							if(userInfor.userCode == ''){
								$(".a-record").on("click",function(){
									lotteryTool.turn("login");
									return;
								});
							}else{
							$(".a-record").on("click",btnClick);
						  }
						}else{
							Login2();
						}
					},
					error : function(err){	
						Login2() ;
						resolve() ;
				}
		});
	})
}

//  查询能否抽奖
const hasRightDraw = function(promotNo){
   return new Promise((resolve,reject) => {
   	   lotteryTool.ajax({
					param : {
						"promotNo": promotNo,
						"userCode": userInfor.userCode, //$("#uid").val()
						"sessionId": userInfor.sessionId//$("#ssid").val()
					},
					port : 'C_APP_3021',  //查询能否抽奖
					success : function(data){						
						let result = data;			
						if(result.returnCode == "000000"){
                            if(result.flag == 0){  // 能抽奖
                            	alert('我能抽奖'+result.flag)
                            	resolve(result.flag)
                            }else{  //已经抽过奖
                            	$(".spinner").hide();
								lotteryTool.lottery.hide();
								var awardRecord = result.drawUserRecord;
								if(awardRecord.couponType == "07"){
									lotteryTool.notWinning.show();
								}else{
									let html = fill(result.drawUserRecord,true);
									lotteryTool.winning.append(html).show();	
								}
								 reject()
                            }
				            
						}else{
						    Login2();	
						}
						
					},
					error : function(err){
						alert('你还没有登录')
						Login2();
					}
		    });
       })
}

//  抽奖
function clickDraw(promotNo){
	return new Promise((resolve,reject)=>{    
       $(".spinner").hide();
        alert('啦啦啦')
		lotteryTool.lottery.show();
		lottery.lottery({
			selector:    '#lottery',
			width:        3,
			height:       3,
			index:        -1,    // 初始位置
			initSpeed:    100,  // 初始转动速度
			aim : function(){
				var self = this;
				lotteryTool.ajax({
					param : {
						"promotNo":promotNo,
						"userCode": userInfor.userCode,//$("#uid").val()
						"sessionId": userInfor.sessionId//$("#ssid").val()
					},
					port : 'C_APP_3020', //抽奖
					success : function(data){
						let result = data ;
						// var result = JSON.stringify(data)
						// alert(result)
						if(result.drawUserRecord.couponType == "04"){
								// var locations = {"4":1,"2":3,"3":6,"-1":4};
								// var locations = {"5":2,"3":4,"-1":7};
								// -1代表随机黄金加息券
								var locations = {"5":1,"3":2,"-1":6};
								self.options.target = (function(num){ 
									num = parseInt(num);return locations[num] || locations['-1'];	
								})(result.drawUserRecord.couponValue);
							}else{
								// 
								self.options.target = lotteryTool.getLocation(result.drawUserRecord.couponType);
							}
							if(result.awardPrize == "07"){
								// var stack = [2,5];
								let stack = [7];
								self.options.target = stack.splice(parseInt(Math.random() * stack.length), 1)[0];
								lotteryTool.isPrize = 0;
							}else{
								lotteryTool.isPrize = 1;
								$(".winnging").append(fill(result.drawUserRecord));
								lotteryTool.winning.append(fill(result.drawUserRecord,true));
							}

					},
					error : function(e){
						self.options.target = 1;
						lotteryTool.isPrize = -1;
						//self.stop();
						alert("网络异常，请退出重新抽取");
					}
				});
			},
			stop: function () {
				$(".mask").show();
				if(lotteryTool.isPrize === 1){
					$(".td_5 a").click(function(){
						lotteryTool.turn("coupon");
					});
					$(".winnging").show();
				}else if(lotteryTool.isPrize === 0){
					$(".not-winning").show();
				}else if(lotteryTool.isPrize === -1){
					//window.location.reload() 
				}
				// 刷新抽奖记录列表
			   adminLotteryRecords(promotNo)
			   allLotteryRecords(promotNo)
				
			}	
		});
	})
}

//用模板编译 
const fill = function(data,flag){
		var html = '';
		if(data.couponType == "01"){ //展示 随机 加息券 仅此一种情况 没有定额的
			html = `<div class="winMask-cont giftMoney">
						<div class="winingInfo">
							<h2>${lotteryTool.parseNum(data.couponValue)}<span>${lotteryTool.getUnit(data.couponType)}</span></h2>
							<p class="prizeName">${lotteryTool.getPrizeName(data.couponType)}</p>
							<p class="p-btn-box"><a href="javascript:${lotteryTool.turn('coupon')}" class="btn">立即查看>></a></p>
						</div>
					   <div class="winBg">
					   	<h3 class="winTit">棒棒哒，<br>明天还会有哦</h3>
							<img src="images/complianceOn-imgs/giftMoney_bg.png">
						</div>
				    </div>`;
		}else{  //展示随机（数字随机）红包，随机（数字）定额黄金加息券 
              html = `<div class="winMask-cont goldLoans goldNum ">
						<div class="winingInfo">
							<h2>${lotteryTool.parseNum(data.couponValue)}<span>${lotteryTool.getUnit(data.couponType)}</span></h2>
							<p class="prizeName">${lotteryTool.getPrizeName(data.couponType)}</p>
							<p class="p-btn-box"><a href="javascript:${lotteryTool.turn('coupon')}" class="btn">立即查看>></a></p>
						</div>
					   <div class="winBg">
					  	<h3 class="winTit">棒棒哒，&nbsp;&nbsp;<br>明天还会有哦</h3>
							<img src="images/complianceOn-imgs/rateCoupon_bg.png">
						</div>
				    </div>`;
		}
		lotteryTool.edmond = lotteryTool.getEdmond(data.couponType);
		return html;
	};
